package com.dragonfly.shutter.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dragonfly.shutter.DAOs.UserDAO;
import com.dragonfly.shutter.beans.UserDetail;
import com.dragonfly.shutter.beans.UserLogin;
import com.dragonfly.shutter.utils.MD5Util;

/**
 * 密码服务类，用于完成和密码有关操作
 * @author jinlingjie
 *
 */
@Service
public class PasswordService {
	@Autowired
	UserDAO userDAO;
	/**
	 * @param userDAO the userDAO to set
	 */
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	/**
	 * 更改密码
	 * @param oldPassword 原密码
	 * @param userDetail 用户详细信息
	 * @return 如果更改成功返回true，否则返回false
	 */
	public boolean changePassword(String oldPassword, UserDetail userDetail)
	{
		UserLogin user = userDAO.selectLoginInfoByEmail(userDetail.getEmail());
		if(user == null)
		{
			return false;
		}
		
		//原密码匹配
		if(!MD5Util.checkpassword(oldPassword, user.getPassword()))
		{
			return false;
		}
		
		//更新用户密码
		userDetail.setPassword(MD5Util.EncoderByMd5(userDetail.getPassword().getBytes()));		//将新密码加密
		if(userDAO.updatePassword(userDetail) != 1)
		{
			return false;
		}
		
		return true;
	}
}
